package com.fyqp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fyqp.mapper.OprHistoryMapper;
import com.fyqp.mapper.ProductTypeMapper;
import com.fyqp.pojo.OprHistory;
import com.fyqp.pojo.Product;
import com.fyqp.mapper.ProductMapper;
import com.fyqp.pojo.ProductType;
import com.fyqp.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyqp.util.BaseResult;
import com.fyqp.util.DateUtil;
import com.fyqp.util.PageUtil;
import com.fyqp.util.ParamUtl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author efire
 * @since 2022-02-05
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Resource
    private ProductMapper productMapper;

    @Resource
    private OprHistoryMapper oprHistoryMapper;

    @Resource
    private ProductTypeMapper productTypeMapper;

    @Override
    public BaseResult oprPro(Product product) {
        String name = product.getName();
        BigDecimal price = product.getPrice();
        if (StringUtils.isBlank(name)) {
            BaseResult.error("名称不能为空");
        }
        if (price == null || price.doubleValue() < 0) {
            BaseResult.error("价格错误");
        }
        trimProduct(product);
        Long id = product.getId();
        Date date = new Date();
        product.setLastUpdateTime(date);
        if (id != null) {
            Product po = productMapper.selectOne(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getId, id)
                            .eq(Product::getIsUse, 1));

            if (po == null) {
                return BaseResult.error("该产品不存在");
            }
            if (getSameProduct(product) != null) {
                return BaseResult.error("已存在相同产品，请勿重复添加");
            }
            product.setId(id);
            updateById(product);
        } else {
            if (getSameProduct(product) != null) {
                return BaseResult.error("已存在相同产品，请勿重复添加");
            }
            product.setAddTime(date);
            save(product);
        }
        return BaseResult.success();
    }

    private Product getSameProduct(Product product) {
        if (product.getId() == null) {
            return productMapper.selectOne(new LambdaQueryWrapper<Product>()
                    .eq(Product::getName, product.getName())
                    .eq(Product::getCarType, product.getCarType())
                    .eq(Product::getMapNum, product.getMapNum())
                    .eq(Product::getIsUse, 1));
        }

        return productMapper.selectOne(new LambdaQueryWrapper<Product>()
                .eq(Product::getName, product.getName())
                .eq(Product::getCarType, product.getCarType())
                .eq(Product::getMapNum, product.getMapNum())
                .ne(Product::getId, product.getId())
                .eq(Product::getIsUse, 1));
    }

    @Override
    public BaseResult queryInfo(Product product) {
        BaseResult result = new BaseResult();
        PageUtil.checkPage(product);
        product.setCondition(StringUtils.trimToEmpty(product.getCondition()));
        result.setReturnData(productMapper.queryLike(product));
        result.setTotal(productMapper.queryLikeNum(product));
        result.setCode(200);
        return result;
    }

    @Override
    public BaseResult queryWithId(Product product) {
        Long id = product.getId();
        if (!ParamUtl.isValidId(id)) {
            return BaseResult.error("id不能为空");
        }
        Product po = productMapper.selectOne(new LambdaQueryWrapper<Product>()
                .eq(Product::getId, id)
                .eq(Product::getIsUse, 1));
        if (po != null) {
            ProductType productType = productTypeMapper.selectById(po.getTypeId());
            if (productType != null) {
                po.setTypeName(productType.getName());
            }
        }
        return BaseResult.success(po);
    }

    @Override
    public BaseResult delPro(Product product) {
        Long id = product.getId();
        if (!ParamUtl.isValidId(id)) {
            return BaseResult.error("id不能为空");
        }
        Product po = productMapper.selectOne(
                new LambdaQueryWrapper<Product>()
                        .eq(Product::getId, id)
                        .eq(Product::getIsUse, 1));

        if (po == null) {
            return BaseResult.error("该产品不存在");
        }
        po.setIsUse(0);
        productMapper.updateById(po);
        return BaseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult oprStock(Product product) {
        Long id = product.getId();
        if (!ParamUtl.isValidId(id)) {
            return BaseResult.error("id不能为空");
        }
        Long stock = product.getStock();
        if (stock == null || stock < 0) {
            return BaseResult.error("库存数量错误");
        }
        Product po = productMapper.selectOne(
                new LambdaQueryWrapper<Product>()
                        .eq(Product::getId, id)
                        .eq(Product::getIsUse, 1));

        if (po == null) {
            return BaseResult.error("该产品不存在");
        }
        Long oldStock = po.getStock();
        long stockGap = stock -oldStock;
        if (stockGap == 0) {
            return BaseResult.success();
        }
        po.setStock(stock);
        po.setLastUpdateTime(new Date());
        updateById(po);
        recordOprHistory(id, stockGap, product.getTime());
        return BaseResult.success();
    }

    @Override
    public BaseResult queryOprHistory(OprHistory history) {
        BaseResult result = new BaseResult();
        PageUtil.checkPage(history);
        history.setCondition(StringUtils.trimToEmpty(history.getCondition()));
        result.setTotal(oprHistoryMapper.queryLikeNum(history));
        result.setCode(200);
        result.setReturnData(oprHistoryMapper.queryLike(history));
        return result;
    }

    private void recordOprHistory(Long id, Long stockGap, String oprTime) {
        OprHistory po = new OprHistory();
        po.setOprTime(oprTime == null ? DateUtil.getNowStr() : oprTime);
        po.setType(stockGap > 0 ? 1 : 2);
        po.setNum(Math.abs(stockGap));
        po.setProductId(id);
        oprHistoryMapper.insert(po);

    }

    private void trimProduct(Product product) {
        product.setName(StringUtils.trimToEmpty(product.getName()));
        product.setCarType(StringUtils.trimToEmpty(product.getCarType()));
        product.setMapNum(StringUtils.trimToEmpty(product.getMapNum()));
        product.setFactory(StringUtils.trimToEmpty(product.getFactory()));
        product.setMark(StringUtils.trimToEmpty(product.getMark()));
    }
}
